using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;

namespace Tools.UI
{
    [RequireComponent(typeof(OnPointerUpEvent))]
    [AddComponentMenu("Tools/UI/OnPointerLongTouch")]
    public class OnPointerLongTouch : MonoBehaviour
    {
        [SerializeField] private float longTouchTime = 1f;
        [SerializeField] private UnityEvent onLongTouch = new UnityEvent();
        public UnityEvent OnLongTouch => onLongTouch;
        private float _touchTime;
        private bool _isTouching;
        private int _pointId;
        private Coroutine _longTouchCoroutine;
        
        private OnPointerUpEvent _onPointerUpEvent;
        
        
        
        private void Awake()
        {
            _onPointerUpEvent = GetComponent<OnPointerUpEvent>();
            _onPointerUpEvent.PointerDownEvent.AddListener(OnPointerDown);
            _onPointerUpEvent.PointerUpEvent.AddListener(OnPointerUp);
        }

        private void OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData)
        {
            if (!_isTouching)
            {
                _isTouching = true;
                _touchTime = Time.time;
                _pointId = eventData.pointerId;
                _longTouchCoroutine = StartCoroutine(RecordTime());
            }
        }

        private void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData)
        {
            if(_isTouching && eventData.pointerId == _pointId)
            {
                _isTouching = false;
                StopCoroutine(_longTouchCoroutine);
                _longTouchCoroutine = null;
            }
        }

        IEnumerator RecordTime()
        {
            while (_isTouching)
            {
                yield return null;
                if (Time.time - _touchTime >= longTouchTime)
                {
                    Debug.Log("Long Touch");
                    _isTouching = false;
                    _longTouchCoroutine = null;
                    onLongTouch?.Invoke();
                }
            }
        }
        
    }
}

